﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using AEM.Data;
using Actions = AEM.Data.BLL.Actions;

namespace AEM
{
    /// <summary>
    /// TrailsMonittoring.xaml 的交互逻辑
    /// </summary>
    public partial class TrailsMonittoring : Window
    {
        public event EventHandler<EventArgs> HideEventHandler;
        private string liftnum = "";
        private Data.Model.LiftInfo liftinfo = null;
        public TrailsMonittoring()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(TrailsMonittoring_Loaded);
            this.TitleBar.MouseLeftButtonDown += new MouseButtonEventHandler(TrailsMonittoring_MouseLeftButtonDown);
            this.btn_close.Click += new RoutedEventHandler(btn_close_Click);
            this.btn_rising.Click += new RoutedEventHandler(btn_rising_Click);
            this.btn_descending.Click += new RoutedEventHandler(btn_descending_Click);
            this.btn_stop.Click += new RoutedEventHandler(btn_stop_Click);

        }

        void TrailsMonittoring_Loaded(object sender, RoutedEventArgs e)
        {
            Data.Model.ClientConfig r = Data.DAL.ClientConfig.Search();
            if (null != r)
            {
                if (null != r.WalkwayInput)
                {
                    List<string> tmp = r.WalkwayInput.Split(',').ToList();
                    if (tmp.Count < 3) { tmp.AddRange((new string[] { "", "", "" })); }
                    if (!string.IsNullOrEmpty(tmp[0])) this.status_udf1.Text = tmp[0];
                    if (!string.IsNullOrEmpty(tmp[1])) this.status_udf2.Text = tmp[1];
                    if (!string.IsNullOrEmpty(tmp[2])) this.status_udf3.Text = tmp[2];
                }
            }
            Actions.LiftInfo.TrailsMonittoring = doTrailsMonittor;
            PortMonitoring.MonitoringIDSign = this.LiftID;
            PortMonitoring.MonitoringSign = true;
        }

        bool isLeftMoving = false;
        bool isRightMoving = false;
        void doTrailsMonittor(SerialDataEventArgs e)
        {
            if (Dispatcher.CheckAccess()) return;
            if (null == e || null == e.Data) return;
            if (this.liftnum != e.LiftNum.ToString()) return;
            Dispatcher.Invoke(new Action(() =>
            {
                //this.faultcode.Text = e.StatusCode;
                //IEnumerable<string> fault = (from r in Config.dataBaseDataset.TableFaultDefinition
                //                             where r.FaultCode == e.StatusCode
                //                             select r.FaultName).Take(1);
                //if (fault.Count() > 0)
                //    this.faultcode.Text += "  " + fault.ToArray<string>()[0];

                // this.status_rising.IsOn = e.Data.Rising;
                if (e.Data.Rising)
                {
                    RotateTransform rt = new RotateTransform();
                    rt.CenterX = 40;
                    rt.CenterY = 14;
                    rt.Angle = 0;
                    this.t_up_down.RenderTransform = rt;
                    if (!isRightMoving)
                    {
                        ((Storyboard)this.TryFindResource("RightStoryboard")).Begin();
                        isRightMoving = true;
                    }
                }
                else
                {
                    ((Storyboard)this.TryFindResource("RightStoryboard")).Stop();
                    isRightMoving = false;
                }

                //this.status_descending.IsOn = e.Data.Descending;
                if (e.Data.Descending)
                {
                    RotateTransform rt = new RotateTransform();
                    rt.CenterX = 40;
                    rt.CenterY = 14;
                    rt.Angle = 180;
                    this.t_up_down.RenderTransform = rt;
                    if (!isLeftMoving)
                    {
                        ((Storyboard)this.TryFindResource("LeftStoryboard")).Begin();
                        isLeftMoving = true;
                    }
                }
                else
                {
                    ((Storyboard)this.TryFindResource("LeftStoryboard")).Stop();
                    isLeftMoving = false;
                }
                this.status_discontinuous.IsOn = e.Data.DisContinuous;
                this.status_continuous.IsOn = e.Data.Continuous;
                this.status_stop.IsOn = e.Stop;
                this.status_estop.IsOn = e.Estop;
                this.status_fault.IsOn = e.Data.FaultLamp;
                this.status_overhaul.IsOn = e.Data.Overhaul;
                this.status_fire.IsOn = e.Data.Fire;
                this.status_earthquake.IsOn = e.Data.IsEarthquaked;
                this.status_local.IsOn = e.Data.Local;
                this.status_udf1.IsOn = e.Data.UDF1;
                this.status_udf2.IsOn = e.Data.UDF2;
                this.status_udf3.IsOn = e.Data.UDF3;
            }));
        }

        void btn_stop_Click(object sender, RoutedEventArgs e)
        {
            if (!Common.PermissionManager.hasPower((int)Data.Enum.ControlPoints.TrailsStopRuning))
            {
                MessageBox.Show((string)TryFindResource("PermissionDenied"));
                return;
            }
            if (null != Actions.SerialPorts.Regulate && null != liftinfo)
                Actions.SerialPorts.Regulate.BeginInvoke(true,
                    liftinfo.LiftNum, liftinfo.LiftCOM, byte.Parse("A", NumberStyles.HexNumber), 0, new AsyncCallback(Actions.SerialPorts.RegulateCallback), null);
        }

        void btn_descending_Click(object sender, RoutedEventArgs e)
        {
            if (!Common.PermissionManager.hasPower((int)Data.Enum.ControlPoints.BackwardStart))
            {
                MessageBox.Show((string)TryFindResource("PermissionDenied"));
                return;
            }
            if (null != Actions.SerialPorts.Regulate && null != liftinfo)
                Actions.SerialPorts.Regulate.BeginInvoke(true,
                    liftinfo.LiftNum, liftinfo.LiftCOM, byte.Parse("9", NumberStyles.HexNumber), 0, new AsyncCallback(Actions.SerialPorts.RegulateCallback), null);
        }

        void btn_rising_Click(object sender, RoutedEventArgs e)
        {
            if (!Common.PermissionManager.hasPower((int)Data.Enum.ControlPoints.ForwardStart))
            {
                MessageBox.Show((string)TryFindResource("PermissionDenied"));
                return;
            }
            if (null != Actions.SerialPorts.Regulate && null != liftinfo)
                Actions.SerialPorts.Regulate.BeginInvoke(true,
                    liftinfo.LiftNum, liftinfo.LiftCOM, byte.Parse("8", NumberStyles.HexNumber), 0, new AsyncCallback(Actions.SerialPorts.RegulateCallback), null);
        }

        void btn_close_Click(object sender, RoutedEventArgs e)
        {
            if (null != HideEventHandler)
                HideEventHandler.Invoke(this, null);
            // this.Close();
        }

        private void sys_button_close_Click(object sender, RoutedEventArgs e)
        {
            if (null != HideEventHandler)
                HideEventHandler.Invoke(this, null);
            // this.Close();
        }
        private void sys_button_min_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private static void OnLiftIDChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            if (args.NewValue != args.OldValue)
            {
                Data.Model.LiftInfo model = Data.DAL.LiftInfo.Select((int)args.NewValue);
                if (null == model) { (sender as TrailsMonittoring).lift_name.Content = (sender as TrailsMonittoring).TryFindResource("NoID") as string; return; }
                InitModelInfo(sender as TrailsMonittoring, model);
            }
        }

        private static void InitModelInfo(TrailsMonittoring m, Data.Model.LiftInfo r)
        {
            m.liftinfo = r;
            m.liftnum = r.LiftNum.ToString();
            m.lift_name.Content = r.LiftNum + "--" + r.LiftSite;
            m.lift_angle.Content = GetAngle(m, r.Angle);
        }

        private static string GetAngle(TrailsMonittoring m, int angle)
        {
            switch (angle)
            {
                case 0:
                    return (string)m.TryFindResource("North");
                case 45:
                    return (string)m.TryFindResource("NorthEast");
                case 90:
                    return (string)m.TryFindResource("East");
                case 135:
                    return (string)m.TryFindResource("SouthEast");
                case 180:
                    return (string)m.TryFindResource("South");
                case -135:
                    return (string)m.TryFindResource("SouthWest");
                case -90:
                    return (string)m.TryFindResource("West");
                case -45:
                    return (string)m.TryFindResource("NorthWest");
            }
            return (string)m.TryFindResource("North");
        }

        void TrailsMonittoring_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        #region 以下注册属性
        /// <summary>
        /// 数据库内电梯信息ID
        /// </summary>
        public static readonly DependencyProperty LiftIDProperty =
            DependencyProperty.Register("LiftID", typeof(int), typeof(TrailsMonittoring),
            new FrameworkPropertyMetadata(0, new PropertyChangedCallback(OnLiftIDChanged)));

        /// <summary>
        /// 数据库内电梯信息ID
        /// </summary>
        public int LiftID
        {
            get { return (int)GetValue(LiftIDProperty); }
            set { SetValue(LiftIDProperty, value); }
        }

        ///// <summary>
        ///// 电梯进行方向,true上行,false下行
        ///// </summary>
        //public static readonly DependencyProperty LiftDirectionProperty =
        //    DependencyProperty.Register("LiftDirection", typeof(bool), typeof(EscalatorMonitoring),
        //    new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnLiftDirectionChanged)));

        ///// <summary>
        ///// 电梯进行方向,true上行,false下行
        ///// </summary>
        //public bool LiftDirection
        //{
        //    get { return (bool)GetValue(LiftDirectionProperty); }
        //    set { SetValue(LiftDirectionProperty, value); }
        //}

        #endregion
    }
}
